import env from './config/env';
import * as Koa from 'koa';
const app = new Koa();
const views = require('koa-views');
const json = require('koa-json');
const onerror = require('koa-onerror');
const bodyparser = require('koa-bodyparser')();
const logger = require('koa-logger');
// import log4jsConfig from './config/log4j.json';

import * as fs from 'fs';
const bodyParser = require('koa-bodyparser');
const session = require('koa-session');
import * as Router from 'koa-router';
const convert = require('koa-convert');
const serve = require('koa-static');
let log4js = require('koa-log4');
import {dingConfig,dingTalkApi } from './node_modules/dingtalk-app'

/* ************************************************* */
// let appenders: any[] = log4jsConfig.appenders;
// if (!fs.existsSync(env.logPath)) {
//   fs.mkdirSync(env.logPath);
// }
// appenders.forEach(value => {
//   let filename: string = value.filename;
//   let path: string = '';
//   if (filename) {
//       path = filename.substring(0, filename.lastIndexOf("/"));
//   }
//   if (value.filename && !fs.existsSync(path)) {
//       fs.mkdirSync(path);
//   }
// });
// log4js.configure(log4jsConfig);
// app.use(log4js.koaLogger(log4js.getLogger("access"), { level: 'auto' }));
/* ************************************************* */

onerror(app);

// middlewares
app.use(bodyparser);
app.use(json());
app.use(logger());
app.use(require('koa-static')(__dirname + '/public'));
//public/images/xxxxxx
app.use(views(__dirname + '/views', {
  extension: 'pug'
}));

// logger

app.use(logger());
app.use(bodyParser());
app.keys = ['some secret hurr'];
app.use(convert(session(app)));
app.use(serve(__dirname + '/public'));

dingConfig.init(app, env as any, [/^\/api\/auth\/*/,/^\/api\/*/]);

//加载路由
let routers_path = __dirname + '/routes/';
let routers = fs.readdirSync(routers_path)
routers.map(file => {
  let mpath = "./routes/";
  let route = require(mpath + file.substring(0, file.lastIndexOf('.')));
  app.use(route.default.routes())
})

export default app;
